import "./lib/wxPromise/wxPromise.min.js";
import to from "lib/await-to-js/await-to-js.es5";
import api from "./api/api.js";
import http from "./utils/request.js";
//app.js
App({
  onLaunch: async function() {
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    this.clearCache();
    this.userAuthrized();
  },

  onShow: async function() {},

  async clearCache() {
    wx.clearStorageSync("userInfo");
    wx.clearStorageSync("token");
  },

  async userAuthrized() {
    //授权
    const result = await wx.pro.getSetting();
    if (result.authSetting["scope.userInfo"]) {
      //如果已经授权
      const { userInfo } = await wx.pro.getUserInfo();
      console.log("userInfo", userInfo);
      if (userInfo) {
        const codeResult = await http.login();
        const { code } = codeResult;

        const data = Object.assign(
          {},
          {
            code
          },
          userInfo
        );

        const [err, res] = await to(
          http.req({
            url: api.WxAuth,
            method: "POST",
            data
          })
        );

        console.log("err", err);
        console.log("请求结果", res);
        if (err) {
          wx.showModal({
            title: "提示",
            content: `请求用户数据失败${JSON.parse(err)}}`,
            showCancel: false
          });
          this.globalData.isAuth = false;
          return;
        }

        wx.setStorageSync("userInfo", userInfo);

        const { openid } = res;

        if (openid) {
          wx.setStorageSync("token", openid);
          this.globalData.isAuth = true;
        } else {
          wx.showModal({
            title: "提示",
            content: "登录失败",
            showCancel: false
          });
          this.globalData.isAuth = false;
        }
      }
    }
  },

  globalData: {
    userInfo: null,
    current: "homepage",
    did: null,
    isAuth: false,
    refreshWash: false
  }
});
